﻿using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Threading.Tasks;
using NetMicro.Cache;
using NetMicro.Cache.Extensions;
using NetMicro.Cache.RedisProvider;
using NetMicro.Core.Extensions;

namespace NetMicro.Cache.DelayBus
{
    public class DelayTaskService : IDelayTaskService
    {
        private readonly IRedisCache _redisCache;
        public DelayTaskService(IRedisCache redisCache)
        {
            _redisCache = redisCache;
        }
        /// <summary>
        /// 添加一个延迟任务
        /// </summary>
        /// <param name="eventJob"></param>
        /// <returns></returns>
        public Task PublishAsync(EventJob eventJob)
        {
            using (var tran = _redisCache.StartPipe())
            {
                tran.PutJob(eventJob);
                tran.PushJobToBucket(eventJob.Topic, eventJob.JobId, eventJob.Delay);
                return Task.CompletedTask;
            }
        }

        /// <summary>
        /// 添加一个延迟任务
        /// </summary>
        /// <param name="eventJob"></param>
        /// <returns></returns>
        public void Publish(EventJob eventJob)
        {
            using (var tran = _redisCache.StartPipe())
            {

                tran.PutJob(eventJob);
                tran.PushJobToBucket(eventJob.Topic, eventJob.JobId, eventJob.Delay);
            }
        }
        /// <summary>
        ///  删除一个延迟任务
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="jobId"></param>
        /// <returns></returns>
        public Task RemoveDealyJobAsync(string topic, string jobId)
        {
            if (string.IsNullOrWhiteSpace(topic))
            {
                throw new ArgumentException($"异常的Topic");
            }
            using (var tran = _redisCache.StartPipe())
            {

                tran.DelJob(jobId);
                tran.RemoveJob(topic, jobId);
                return Task.CompletedTask;
            }
        }

        /// <summary>
        ///  删除一个延迟任务
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="jobId"></param>
        /// <returns></returns>
        public void RemoveDealyJob(string topic, string jobId)
        {
            if (string.IsNullOrWhiteSpace(topic))
            {
                throw new ArgumentException($"异常的Topic");
            }
            using (var tran = _redisCache.StartPipe())
            {

                tran.DelJob(jobId);
                tran.RemoveJob(topic, jobId);
            }
        }
    }
}
